#include <iostream>
#include <cassert>
#include <typeinfo>
#include <string>
#include <unistd.h>
class Any
{
public:
    Any() {}
    template <class T>
    Any(const T &val) : _content(new placeholder<T>(val))
    {
    }
    Any(const Any &other) : _content(other._content ? other._content->clone() : nullptr) {}
    ~Any() { delete _content; }

    Any swap(Any &other)
    {
        std::swap(_content, other._content);
        return *this;
    }

    // 返回子类保存数据的指针
    template <class T>
    T *get()
    {
        assert(typeid(T) == _content->type());
        return &((placeholder<T> *)_content)->_val;
    }

    Any &operator=(const Any &other)
    {
        Any(other).swap(*this);
        return *this;
    }
    template <class T>
    Any &operator=(const T &val)
    {
        Any(val).swap(*this);
        return *this;
    }

private:
    class holder
    {
    public:
        holder() {}
        virtual ~holder() {}
        virtual const std::type_info &type() = 0; // 获取类型
        virtual holder *clone() = 0;              // 克隆
    };
    template <class T>
    class placeholder : public holder
    {
    public:
        placeholder(const T &val) : _val(val) {}
        ~placeholder() {}
        const std::type_info &type() { return typeid(T); }
        holder *clone() { return new placeholder<T>(_val); }

    public:
        T _val;
    };
    holder *_content;
};

class Test
{
public:
    Test() { std::cout << "构造" << std::endl; }
    Test(const Test &t) { std::cout << "拷贝" << std::endl; }
    ~Test() { std::cout << "析构" << std::endl; }
};

int main()
{
    Any y;
    {
        Test t;
        y = t;
    }
    // y=1;
    // int *a = y.get<int>();
    // std::cout<<*a<<std::endl;
    // y=std::string("hello");
    // std::string* str = y.get<std::string>();
    // std::cout<<*str<<std::endl;
    sleep(3);
    return 0;
}